SET enable_analyzer = 1;
SET enable_parallel_replicas = 1, max_parallel_replicas = 2, cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost';
SET parallel_replicas_mark_segment_size = 1;

DROP TABLE IF EXISTS test_table_join_1 SYNC;
CREATE TABLE test_table_join_1
(
    id UInt8,
    value String
) ENGINE = ReplicatedMergeTree('/clickhouse/{database}/test_table_join_1', 'r1') ORDER BY id SETTINGS index_granularity=1;

DROP TABLE IF EXISTS test_table_join_2 SYNC;
CREATE TABLE test_table_join_2
(
    id UInt16,
    value String
) ENGINE = ReplicatedMergeTree('/clickhouse/{database}/test_table_join_2', 'r1') ORDER BY id SETTINGS index_granularity=1;

DROP TABLE IF EXISTS test_table_join_3 SYNC;
CREATE TABLE test_table_join_3
(
    id UInt64,
    value String
) ENGINE = ReplicatedMergeTree('/clickhouse/{database}/test_table_join_3', 'r1') ORDER BY id SETTINGS index_granularity=1;

INSERT INTO test_table_join_1 SELECT number, concat('t1_value_', number) from numbers(500);
INSERT INTO test_table_join_1 SELECT number, concat('t1_value_', number) from numbers(500, 400);

INSERT INTO test_table_join_2 SELECT number, concat('t2_value_', number) from numbers(100, 500);
INSERT INTO test_table_join_2 SELECT number, concat('t2_value_', number) from numbers(500, 500);

INSERT INTO test_table_join_3 SELECT number, concat('t3_value_', number) from numbers(500);
INSERT INTO test_table_join_3 SELECT number, concat('t3_value_', number) from numbers(600, 400);

-- { echoOn }

{% for parallel_replicas_local_plan in ['0', '1'] -%}
{% for first_join_type in ['INNER'] -%}
{% for second_join_type in ['INNER', 'LEFT', 'RIGHT', 'FULL'] -%}

SELECT 'First JOIN {{ first_join_type }} second JOIN {{ second_join_type }}';

SELECT
    id AS using_id,
    t1.id AS t1_id,
    t1.value AS t1_value,
    t2.id AS t2_id,
    t2.value AS t2_value,
    t3.id AS t3_id,
    t3.value AS t3_value
FROM test_table_join_1 AS t1
{{ first_join_type }} JOIN test_table_join_2 AS t2 USING (id)
{{ second_join_type }} JOIN test_table_join_3 AS t3 USING (id)
ORDER BY ALL ASC
SETTINGS parallel_replicas_local_plan={{ parallel_replicas_local_plan }};

{% endfor %}
{% endfor %}
{% endfor %}

-- { echoOff }

DROP TABLE test_table_join_1 SYNC;
DROP TABLE test_table_join_2 SYNC;
DROP TABLE test_table_join_3 SYNC;
